package com.cne.gmail.Gmail.Excutor;


import com.cne.gmail.Gmail.Handle.GmailHandle;
import com.cne.gmail.Gmail.model.UserModel;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.model.History;
import com.google.api.services.gmail.model.HistoryMessageAdded;
import com.google.api.services.gmail.model.ListHistoryResponse;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 处理监控的消息，导入数据库和发送消息给前端
 */
public class AscWatchMailChange  {
    private UserModel user;
    private static Logger logger = LoggerFactory.getLogger("AscWatchMailChange");
    public AscWatchMailChange( UserModel user){
        this.user=user;
    }
    public Map call() throws GeneralSecurityException, IOException {
        Map<String, Set<String>> map= Maps.newHashMap();
        Gmail service= GmailHandle.service(user);
        List<History> histories = new ArrayList<History>();
        ListHistoryResponse historyresponse = service.users().history().list("me")
                                                 .setStartHistoryId(BigInteger.valueOf(Long.valueOf(user.getHistoryId()))).execute();
        while (historyresponse.getHistory() != null) {
            histories.addAll(historyresponse.getHistory());
            if (historyresponse.getNextPageToken() != null) {
                String pageToken = historyresponse.getNextPageToken();
                    historyresponse = service.users().history().list("me").setPageToken(pageToken)
                                 .setStartHistoryId(BigInteger.valueOf(Long.valueOf(user.getHistoryId()))).execute();
            } else {
                break;
            }
        }
        Set sentLabel= Sets.newHashSet();
        Set inboxLabel= Sets.newHashSet();
        for (History history : histories) {
            if (history.getMessagesAdded()!=null){
                for (HistoryMessageAdded historyMessageAdded:history.getMessagesAdded()){
                    for (String labelId:historyMessageAdded.getMessage().getLabelIds()){
                        if (labelId.equals("SENT")){
                            sentLabel.add(historyMessageAdded.getMessage().getId());
                            map.put(labelId,sentLabel);
                        }else if (labelId.equals("INBOX")){
                            inboxLabel.add(historyMessageAdded.getMessage().getId());
                            map.put(labelId,inboxLabel);
                        }
                    }
                }
            }
        }
        return map;
    }
}
